package com.mvp.images;

/**
 * Created by linet on 2017/8/22.
 */

import android.content.Context;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.mvp.R;

import timber.log.Timber;

/**
 * Created by zhangyuncai on 2018/9/11.
 */
public final class WImageLoader {

    private WImageLoader() {
    }

    /**
     * 默认加载图片的方法
     *
     * @param context
     * @param uri
     * @param imageView
     */
    public static void displayImage(Context context, String uri, ImageView imageView) {
        displayImage0(context, uri, imageView, 0, 0, 0);
    }

    /**
     * @param context
     * @param uri
     * @param imageView
     * @param errorDrawableId 加载失败后的默认图片
     */
    public static void displayImage(Context context, String uri, ImageView imageView, @DrawableRes int errorDrawableId) {
        displayImage0(context, uri, imageView, errorDrawableId, errorDrawableId, errorDrawableId);
    }


    private static void displayImage0(Context context, String uri, ImageView imageView, @DrawableRes int loadingDrawable, @DrawableRes int errorDrawable, @DrawableRes int netDrawable) {
        Timber.d("-------------->ImageHelper.addImageDomain(uri)=" + ImageHelper.addImageDomain(uri));
        if (context == null) {
            return;
        }
        try {
            RequestOptions option = getOption(loadingDrawable, errorDrawable, netDrawable);
            Glide.with(context)
                    .load(ImageHelper.addImageDomain(uri))
                    .apply(option)
                    .into(imageView);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 默认加载显示
     * 此方法d等ui确定后还需要添加默认的loading、error、null图片
     *
     * @return
     */
    private static RequestOptions getOption(@DrawableRes int loadingDrawable, @DrawableRes int errorDrawable, @DrawableRes int netDrawable) {
        RequestOptions options = new RequestOptions();
        options.centerCrop();
        if (loadingDrawable != 0) {
            options.placeholder(loadingDrawable);//加载中默认图片
        }else {
            options.placeholder(R.drawable.ic_load_default);
        }
        if (errorDrawable != 0) {
            options.error(errorDrawable);//  加载错误默认图片
        }else {
            options.error(R.drawable.ic_load_default);
        }
        if (netDrawable != 0) {
            options.fallback(netDrawable);//请求url/model为空
        }else {
            options.fallback(R.drawable.ic_load_default);
        }
        options.diskCacheStrategy(DiskCacheStrategy.ALL);
        options.skipMemoryCache(false);//跳过内存缓存

        return options;
    }


}
